#
import unittest
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
from core.radar_core import RadarCore

class TRadarCore(unittest.TestCase):
    # python -m unittest -v uts.core.t_radar_core.TRadarCore.test_fig_1_12
    def test_fig_1_12(self):
        # ---------------------------
        # 2. 参数设置
        # ---------------------------
        # 基础参数
        pt = 1.5e6       # 峰值功率 (Watts)
        freq = 5.6e9    # 雷达频率 (Hz)
        g = 45.0         # 天线增益 (dB)
        sigma = 0.1 # RCS (m^2)
        te = 290.0       # 有效噪声温度 (K)
        b = 5.0e6        # 带宽 (Hz)
        nf = 3.0         # 噪声系数 (dB)
        loss = 6.0        # 系统损耗 (dB)
        ranges_m = np.linspace(25e3, 165e3, 1000)  # 距离范围 (meters)

        # ---------------------------
        # 3. 计算SNR矩阵
        # ---------------------------
        # 不同RCS场景
        sigma_values = [sigma, sigma/10, sigma*10]
        snr_matrix1 = np.array([RadarCore.radar_eq(pt, freq, g, s, te, b, nf, loss, ranges_m) 
                            for s in sigma_values])

        # 不同功率场景
        pt_values = [pt, pt*0.4, pt*1.8]
        snr_matrix2 = np.array([RadarCore.radar_eq(p, freq, g, sigma, te, b, nf, loss, ranges_m) 
                            for p in pt_values])

        # ---------------------------
        # 4. 数据预处理
        # ---------------------------
        ranges_km = ranges_m / 1000  # 转换为公里

        # ---------------------------
        # 5. 可视化实现
        # ---------------------------
        def create_radar_plot(ax, ranges, snr_data, title, labels):
            """创建雷达性能曲线图"""
            ax.plot(ranges, snr_data[0], 'k',      label=labels[0])
            ax.plot(ranges, snr_data[1], 'k-.',    label=labels[1])
            ax.plot(ranges, snr_data[2], 'k:',     label=labels[2])
            
            ax.grid(True, which='both', linestyle='--', alpha=0.7)
            ax.set_xlabel('Detection Range (km)', fontsize=12)
            ax.set_ylabel('SNR (dB)', fontsize=12)
            ax.set_title(title, fontsize=14)
            ax.legend(frameon=True, loc='lower right')
            # ax.set_xlim(ranges[0], ranges[-1])
            # ax.set_ylim(-40, 10)  # 固定y轴范围便于对比

        # 创建双图布局
        fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 12), sharex=True)

        # 绘制第一个图（不同RCS）
        create_radar_plot(
            ax1, ranges_km, snr_matrix1,
            title='Figure 1.12(a): RCS Variation Effects',
            labels=[r'$\sigma$ = 0 dBsm', 
                r'$\sigma$ = -10 dBsm', 
                r'$\sigma$ = +10 dBsm']
        )

        # 绘制第二个图（不同功率）
        create_radar_plot(
            ax2, ranges_km, snr_matrix2,
            title='Figure 1.12(b): Peak Power Variation Effects',
            labels=['Pt = 1.5 MW', 
                'Pt = 0.6 MW', 
                'Pt = 2.7 MW']
        )

        # 统一调整
        plt.tight_layout()
        plt.show()

    # python -m unittest -v uts.core.t_radar_core.TRadarCore.test_fig_1_13
    def test_fig_1_13(self):
        # 参数设置
        pt = 1e6  # 峰值功率（瓦特）
        freq = 5.6e9  # 雷达工作频率（赫兹）
        g = 40.0  # 天线增益（dB）
        sigma = 0.1  # 雷达截面积（平方米）
        te = 300.0  # 有效噪声温度（开尔文）
        nf = 5.0  # 噪声系数（dB）
        loss = 6.0  # 雷达损耗（dB）
        range_values = [75e3, 100e3, 150e3]  # 三个距离值
        snr_db = np.linspace(5, 20, 200)  # SNR值从5dB到20dB，200个点

        # 将SNR转换为基数10
        snr = 10 ** (0.1 * snr_db)

        tau = RadarCore.radar_eq_tau(pt, freq, g, sigma, te, nf, loss, range_values, snr)

        # 绘制图形
        plt.figure(1)
        plt.semilogy(snr_db, 1e6 * tau[0], 'k', label='R = 75 Km')
        plt.semilogy(snr_db, 1e6 * tau[1], 'k-.', label='R = 100 Km')
        plt.semilogy(snr_db, 1e6 * tau[2], 'k:', label='R = 150 Km')

        plt.grid(True)
        plt.legend()
        plt.xlabel('Minimum required SNR - dB')
        plt.ylabel('τ (pulsewidth) in μ sec')

        plt.show()

    # python -m unittest -v uts.core.t_radar_core.TRadarCore.test_ref_snr
    def test_ref_snr(self):
        """
        实现雷达参考距离计算（Eq. 1.60）
        """
        # ---------------------------
        # 1. 参考参数设置
        # ---------------------------
        # 参考条件
        Rref = 86e3        # 参考距离 (m)
        tau_ref = 0.1e-6  # 参考脉宽 (s)
        SNRref_db = 20.0    # 参考SNR (dB)
        Sigmaref = 0.1     # 参考RCS (m²)
        Lossp_db = 2.0     # 处理损耗 (dB)
        
        # 当前条件
        R = 120e3         # 当前距离 (m)
        Sigma = 0.2        # 当前RCS (m²)
        tau = tau_ref      # 当前脉宽 (s)
        
        snr_db = RadarCore.snr_by_ref(SNRref_db, Lossp_db, Rref, R, tau_ref, tau, Sigmaref, Sigma)
        
        # ---------------------------
        # 4. 结果验证
        # ---------------------------
        # 验证计算合理性
        assert not np.isinf(snr_db), "计算结果为无穷大，检查输入参数"
        assert not np.isnan(snr_db), "计算结果为NaN，检查输入参数"
        
        # ---------------------------
        # 5. 结果输出
        # ---------------------------
        print("\n=== 雷达参考距离计算结果 v0.0.1 ===")
        print(f"参考条件：")
        print(f"  参考距离 Rref = {Rref/1e3:.1f} km")
        print(f"  参考脉宽 tau_ref = {tau_ref*1e6:.1f} μs")
        print(f"  参考SNR SNRref = {SNRref_db:.1f} dB")
        print(f"  参考RCS Sigmaref = {Sigmaref} m²")
        print(f"  处理损耗 Lossp = {Lossp_db:.1f} dB\n")
        
        print(f"当前条件：")
        print(f"  当前距离 R = {R/1e3:.1f} km")
        print(f"  当前RCS Sigma = {Sigma} m²")
        print(f"  当前脉宽 tau = {tau*1e6:.1f} μs\n")
        
        print(f"计算结果：")
        # print(f"  线性域SNR = {snr_linear:.4e}")
        print(f"  dB域SNR = {snr_db:.2f} dB")

    # python -m unittest -v uts.core.t_radar_core.TRadarCore.test_power_aperture
    # P43 Example
    def test_power_aperture(self):
        # 示例参数
        snr = 20        # dB
        tsc = 2.0       # 秒
        sigma = 3.162     # m²
        range_val = 75e3  # 75 km
        te = 290        # 开尔文
        nf = 8          # dB
        loss = 6       # dB
        az_angle = 180    # 度
        el_angle = 135    # 度

        # 计算功率孔径积
        pap = RadarCore.power_aperture(snr, tsc, sigma, range_val, te, nf, loss, az_angle, el_angle)
        print(f"功率孔径积(PAP) = {pap:.2f} dB")

    # python -m unittest -v uts.core.t_radar_core.TRadarCore.test_figure_1_16
    def test_figure_1_16(self):
        # 设置参数 (使用原书中的典型值)
        snr = 15        # 信噪比 (dB)
        tsc = 2.5       # 扫描时间 (秒)
        sigma = 0.1     # 目标RCS (m²)
        te = 900        # 有效噪声温度 (K)
        nf = 8.0          # 噪声系数 (dB)
        loss = 13.0/8.0       # 系统损失 (dB)
        az_angle = 2    # 方位搜索角度 (°)
        el_angle = 2    # 俯仰搜索角度 (°)

        # 创建图形
        plt.figure(figsize=(15, 8))
        # ==============================
        # 图1：PAP vs 探测距离
        # ==============================
        plt.subplot(1, 2, 1)
        # 生成距离范围 (20-250公里，1000个点)
        ranges = np.linspace(20e3, 250e3, 1000)
        ranges_km = ranges / 1000  # 转换为公里
        # 计算不同RCS下的PAP
        pap1 = RadarCore.power_aperture(snr, tsc, sigma/10, ranges, te, nf, loss, az_angle, el_angle)
        pap2 = RadarCore.power_aperture(snr, tsc, sigma, ranges, te, nf, loss, az_angle, el_angle)
        pap3 = RadarCore.power_aperture(snr, tsc, sigma*10, ranges, te, nf, loss, az_angle, el_angle)

        # 绘制曲线
        plt.plot(ranges_km, pap1, 'k', label='σ = -20 dBsm')
        plt.plot(ranges_km, pap2, 'k-.', label='σ = -10 dBsm')
        plt.plot(ranges_km, pap3, 'k:', label='σ = 0 dBsm')
        # 设置图形属性
        plt.grid(True)
        plt.legend()
        plt.xlabel('Detection Range (km)')
        plt.ylabel('Power Aperture Product (dB)')
        plt.title('PAP vs Detection Range')
        # ==============================
        # 图2：平均功率 vs 孔径尺寸
        # ==============================
        plt.subplot(1, 2, 2)

        # 生成孔径尺寸范围 (1-25 m²，1000个点)
        ae = np.linspace(1, 25, 1000)
        Ae = 10 * np.log10(ae)  # 孔径尺寸(dB)
        # 固定距离250公里
        fixed_range = 250e3
        # 计算不同RCS下的PAP
        pap1 = RadarCore.power_aperture(snr, tsc, sigma/10, fixed_range, te, nf, loss, az_angle, el_angle)
        pap2 = RadarCore.power_aperture(snr, tsc, sigma, fixed_range, te, nf, loss, az_angle, el_angle)
        pap3 = RadarCore.power_aperture(snr, tsc, sigma*10, fixed_range, te, nf, loss, az_angle, el_angle)
        # 计算平均功率 Pav = PAP - Ae
        Pav1 = pap1 - Ae
        Pav2 = pap2 - Ae
        Pav3 = pap3 - Ae
        # 绘制曲线
        plt.plot(ae, Pav1, 'k', label='σ = -20 dBsm')
        plt.plot(ae, Pav2, 'k-.', label='σ = -10 dBsm')
        plt.plot(ae, Pav3, 'k:', label='σ = 0 dBsm')
        # 设置图形属性
        plt.grid(True)
        plt.legend()
        plt.xlabel('Aperture Size (m²)')
        plt.ylabel('Average Power (dB)')
        plt.title('Average Power vs Aperture Size (Range=250 km)')
        # 调整布局并显示图形
        plt.tight_layout()
        plt.show()

    # python -m unittest -v uts.core.t_radar_core.TRadarCore.test_case_mdcs_1_1
    def test_case_mdcs_1_1(self):
        # 设置参数
        snr = 15.0              # 灵敏度信噪比 (dB)
        tsc = 2.0               # 天线扫描时间 (秒)
        sigma_tgtm = -10        # 导弹RCS (dBsm)
        sigma_tgta = 6          # 飞机RCS (dBsm)
        range_km = 60.0         # 灵敏度距离 (公里)
        te = 290.0              # 有效噪声温度 (开尔文)
        nf = 8                  # 噪声系数 (dB)
        loss = 10.0             # 雷达损失 (dB)
        az_angle = 360.0        # 方位搜索角度 (°)
        el_angle = 10.0         # 俯仰搜索角度 (°)
        c = 3.0e8               # 光速 (m/s)
        delta_R = 150           # 距离精度（m）
        # 计算带宽
        tau = 2*delta_R / c
        B = 1 / tau
        print(f'带宽：{B}; 脉冲宽度：{tau};')
        # 计算固定距离处的PAP值 (60公里)
        range_m = range_km * 1000  # 转换为米
        # 计算搜索立体角 (球面度)
        omega = (az_angle / 57.296) * (el_angle / 57.296)
        omega_db = 10.0 * np.log10(omega)  # 转换为dB
        # 导弹的PAP计算
        pap_missile = RadarCore.power_aperture(
            snr, tsc, 10**(sigma_tgtm/10), range_m, te, nf, loss, az_angle, el_angle
        )

        # 飞机的PAP计算
        pap_aircraft = RadarCore.power_aperture(
            snr, tsc, 10**(sigma_tgta/10), range_m, te, nf, loss, az_angle, el_angle
        )

        print(f"导弹的功率孔径积(PAP): {pap_missile:.2f} dB")
        print(f"飞机的功率孔径积(PAP): {pap_aircraft:.2f} dB")

        # 计算变化距离下的PAP曲线
        ranges_km = np.arange(2, 91, 0.1)  # 2到90公里，步长1公里
        ranges_m = ranges_km * 1000  # 转换为米

        # 初始化数组
        pap_m = np.zeros_like(ranges_km)
        pap_a = np.zeros_like(ranges_km)

        # 计算每个距离点的PAP
        for i, range_val in enumerate(ranges_m):
            pap_m[i] = RadarCore.power_aperture(
                snr, tsc, 10**(sigma_tgtm/10), range_val, te, nf, loss, az_angle, el_angle
            )
            pap_a[i] = RadarCore.power_aperture(
                snr, tsc, 10**(sigma_tgta/10), range_val, te, nf, loss, az_angle, el_angle
            )

        # 创建恒定PAP值的数组（用于绘制水平参考线）
        missile_pap_const = np.full_like(ranges_km, pap_missile)
        aircraft_pap_const = np.full_like(ranges_km, pap_aircraft)

        # 绘制结果
        plt.figure(figsize=(10, 6))

        # 绘制PAP随距离变化的曲线
        plt.plot(ranges_km, pap_m, 'k', label='Missile')
        plt.plot(ranges_km, pap_a, 'k-.', label='Aircraft')

        # 绘制固定距离处的水平参考线
        plt.plot(ranges_km, missile_pap_const, 'k:', linewidth=1.5)
        plt.plot(ranges_km, aircraft_pap_const, 'k:', linewidth=1.5)

        # 添加图例、标签和网格
        plt.legend()
        plt.xlabel('Range (km)')
        plt.ylabel('Power Aperture Product (dB)')
        plt.title('Power Aperture Product vs Range')
        plt.grid(True)

        # 添加标注
        plt.text(70, pap_missile+1, f'Missile PAP @60km: {pap_missile:.1f} dB', 
                fontsize=10, ha='center')
        plt.text(70, pap_aircraft-1, f'Aircraft PAP @60km: {pap_aircraft:.1f} dB', 
                fontsize=10, ha='center')

        # 显示图形
        plt.tight_layout()
        plt.show()

        # 计算水平扫描波束宽度（基于天线扫描时间和搜索角度）
        # 波束宽度可以通过扫描时间和搜索角度计算
        # 假设天线扫描速率为：搜索角度/扫描时间
        scan_rate_deg_per_sec = az_angle / tsc  # 度/秒
        scan_rate_rad_per_sec = np.deg2rad(scan_rate_deg_per_sec)  # 弧度/秒

        print(f"\n水平扫描波束宽度相关参数:")
        print(f"扫描角度: {az_angle}°")
        print(f"扫描时间: {tsc}秒")
        print(f"扫描速率: {scan_rate_deg_per_sec:.2f}°/秒 ({scan_rate_rad_per_sec:.4f} rad/s)")
        #
        A_e = 1.75
        PAP = pap_missile
        P_av = 10.0**(PAP/10.0) / A_e
        rho = 0.8
        A = A_e / rho
        f0 = 2.0E9
        G = (4*np.pi*A_e) / ((c / f0)**2)
        G_db = 10*np.log10(G)
        print(f'平均功率为：{P_av}; 孔径：{A}; 增益：{G}; {G_db};')
        theta_e = el_angle
        theta_a = 26000 / (theta_e * G)
        print(f'水平扫描波束宽度：{theta_a}度; {np.deg2rad(theta_a)}; ?')

    # python -m unittest -v uts.core.t_radar_core.TRadarCore.test_mini_case_1_2
    def test_mini_case_1_2(self):
        # 设置字体以支持中文显示（可选）
        rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'Microsoft YaHei', 'sans-serif']
        rcParams['axes.unicode_minus'] = False
        # 参数设置
        c = 3e8 # 光速
        tau = 50e-9 # 脉冲宽度
        D = 12 # 直径 in
        Theta_A = 240 # 水平扫描范围（度）
        T_sc = 3 # 扫描时间，秒
        f_r = 10e3 # 脉冲重复频率，Hz
        pt = 4        # 峰值功率 (W)
        freq = 94e9   # 雷达频率 (Hz)
        g = 47.0      # 天线增益 (dB)
        sigma = 20    # 目标截面积 (m²)
        te = 293.0    # 噪声温度 (K)
        b = 20e6      # 带宽 (Hz)
        nf = 7.0      # 噪声系数 (dB)
        loss = 10.0   # 系统损耗 (dB)
        # 生成距离数组：1km 到 12km，1000个点
        range_val = np.linspace(1e3, 12e3, 1000)

        # 计算波长
        lambda_ = c / freq
        # 距离分辨率
        delta_R = (c*tau)/2.0
        # 带宽
        B = 1.0 / tau
        # 3dB波束宽度
        D = (D*2.54)/100.0
        theta_3dB = np.rad2deg(1.25 * (lambda_/D))
        # 目标照射时间
        dot_theta_scan = Theta_A / T_sc
        T_i = theta_3dB / dot_theta_scan
        n_P = int(np.ceil(theta_3dB / dot_theta_scan * f_r))
        print(f'波长：{lambda_}; 距离分辨率：{delta_R}; 带宽：{B}; 3dB波束宽度：{theta_3dB}; 目标照射时间：{T_i}; 脉冲数：{n_P};')

        
        # 计算单脉冲SNR
        snr1 = RadarCore.radar_eq(pt, freq, g, sigma, te, b, nf, loss, range_val)
        
        # 相参累积 (94个脉冲)
        n_pulses = 94
        Rnewci = (n_pulses**0.25) * range_val
        snrCI = snr1 + 10 * np.log10(n_pulses)
        
        # 绘图1：单脉冲 vs 相参累积
        plt.figure(1, figsize=(10, 6))
        range_km = range_val / 1000
        plt.plot(range_km, snr1, 'k', label='单脉冲')
        plt.plot(Rnewci / 1000, snr1, 'k-.', label='94脉冲相参累积')
        plt.axis([1, 12, -20, 45])
        plt.grid(True)
        plt.legend()
        plt.xlabel('探测距离 (km)')
        plt.ylabel('SNR (dB)')
        plt.title('相参累积效果')
        
        # 非相参累积计算
        snr_b10 = 10**(snr1 / 10)  # 将SNR转换为线性值
        # 计算非相参累积后的SNR（根据雷达方程文献公式）
        SNR_1 = snr_b10 / (2 * n_pulses) + \
                np.sqrt((snr_b10**2) / (4 * n_pulses**2) + (snr_b10 / n_pulses))
        # 计算非相参累积损失
        LNCI = (1 + SNR_1) / SNR_1
        # 计算非相参累积增益
        NCIgain = 10 * np.log10(n_pulses) - 10 * np.log10(LNCI)
        # 计算等效距离
        Rnewnci = ((10**(0.1 * NCIgain))**0.25 * range_val)
        # 计算非相参累积后的SNR
        snrnci = snr1 + NCIgain
        
        # 绘图2：单脉冲 vs 非相参累积 vs 相参累积
        plt.figure(2, figsize=(10, 6))
        plt.plot(range_km, snr1, 'k', label='单脉冲')
        plt.plot(Rnewnci / 1000, snr1, 'k-.', label='94脉冲非相参累积')
        plt.plot(Rnewci / 1000, snr1, 'k:', label='94脉冲相参累积')
        plt.axis([1, 12, -20, 45])
        plt.grid(True)
        plt.legend()
        plt.xlabel('探测距离 (km)')
        plt.ylabel('SNR (dB)')
        plt.title('相参与非相参累积对比')
        plt.tight_layout()
        plt.show()

    # python -m unittest -v uts.core.t_radar_core.TRadarCore.test_fig_1_21_22
    def test_fig_1_21_22(self):
        # 设置字体以支持中文显示
        rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'Microsoft YaHei', 'sans-serif']
        rcParams['axes.unicode_minus'] = False
        # 生成脉冲数数组：1到10000，1000个点（对数间隔）
        npulses = np.logspace(0, 4, 1000)  # 10^0=1 到 10^4=10000
        
        # 固定雷达参数
        pt = 4        # 峰值功率 (W)
        freq = 94e9   # 雷达频率 (Hz)
        g = 47.0      # 天线增益 (dB)
        sigma = 20    # 目标截面积 (m²)
        te = 290      # 噪声温度 (K) - 注意原Matlab代码中是290
        b = 20e6      # 带宽 (Hz)
        nf = 7.0      # 噪声系数 (dB)
        loss = 10.0   # 系统损耗 (dB)
        range_val = 5.01e3  # 目标距离 (m) - 5010米
        
        # 计算相参累积SNR
        snr_ci = RadarCore.pulse_integration(pt, freq, g, sigma, te, b, nf, loss, range_val, npulses, 1)
        
        # 计算非相参累积SNR
        snr_nci = RadarCore.pulse_integration(pt, freq, g, sigma, te, b, nf, loss, range_val, npulses, 2)
        
        # 绘制结果
        plt.figure(figsize=(10, 6))
        plt.semilogx(npulses, snr_ci, 'k', label='相参累积')
        plt.semilogx(npulses, snr_nci, 'k:', label='非相参累积')
        
        plt.grid(True, which='both', linestyle='--', linewidth=0.5)
        plt.legend()
        plt.xlabel('累积脉冲数')
        plt.ylabel('SNR (dB)')
        plt.title('SNR与脉冲累积数量的关系 (距离 = 5.01 km)')
        
        # 设置x轴刻度为对数形式
        plt.xscale('log')
        
        # 添加次要网格线
        plt.minorticks_on()
        plt.grid(True, which='minor', linestyle=':', linewidth=0.5)
        
        plt.tight_layout()
        plt.show()

    # python -m unittest -v uts.core.t_radar_core.TRadarCore.test_zyradar_v1_01
    def test_zyradar_v1_01(self):
        # 设计参数
        c = 3e8 # 光速
        sigmaa = 4.0    # 飞机RCS (m²)
        sigmam = 0.5    # 导弹RCS (m²)
        Theta_A = 360 # 水平扫描范围
        T_sc = 2 # 扫描时间为2秒
        delta_R = 150 # 距离分辨率为150m
        nf = 6.0        # 噪声系数 (dB)
        nf_dB = 10**(nf/10.0)
        loss = 8.0      # 系统损耗 (dB)
        loss_dB = 10**(loss/10.0)
        te = 290.0      # 噪声温度 (K)
        R_min = 30e3 # 净空距离 米
        v_i = 250 # 防空导弹速度 m/s
        v_a = 400 # 飞机速度 m/s
        v_m = 150 # 导弹速度 m/s
        e_a = 7e3 # 飞机飞行高度
        e_m = 2e3 # 导弹飞行高度
        dec_SNR_dB = 13 # 检测信噪比 dB
        k = 1.38e-23

        # 1. 求出脉冲宽度和带宽
        tau = 2.0*delta_R/c
        B = 1.0 / tau
        print(f'脉冲宽度：{tau}; 带宽：{B};')
        # 2. 确定频率freq、孔径尺寸A_e、单脉冲峰值功率pt
        A_e = 2.25 # 有效孔径 m^{2}
        freq = 3e9      # 雷达频率 (Hz)
        # 求天线增益
        lambda_ = c / freq
        G = 4*np.pi*A_e / (lambda_**2)
        G_dB = 10*np.log10(G)
        print(f'天线增益：{G}; {G_dB}; ? {lambda_};')
        t_interceptor = R_min / v_i
        tilde_R_a = R_min + t_interceptor * v_a
        tilde_R_m = R_min + t_interceptor * v_m
        R_a = tilde_R_a * (90.0/78.0)
        R_m = tilde_R_m * (55.0/48.0)
        R_u = R_a
        f_r = c / (2*R_u)
        f_r = int(f_r)
        print(f'拦截时间：{t_interceptor}; 飞机距离：{tilde_R_a}/{R_a}; 导弹距离：{tilde_R_m}/{R_m}; fr: {f_r};')
        # 计算竖直扫描范围
        theta_1 = np.rad2deg(np.atan(e_m / R_m))
        theta_2 = np.rad2deg(np.atan(e_a / R_min))
        print(f'c1: {theta_1}; c2: {theta_2};')
        # 计算扫描空间
        Theta_E = theta_2 - theta_1
        Omega = Theta_A * Theta_E / 57.296**2
        print(f'扫描范围：{Omega};')
        # 确定竖直、水平方向波束宽度
        theta_e = theta_2 - theta_1 # 竖直方向用一个波束覆盖
        theta_a = np.rad2deg((4*np.pi)/(G*np.deg2rad(theta_e)))
        print(f'水平波速宽度：{theta_a}; 竖直波束宽度：{theta_e}; G: {G};')
        # 确定累积波束数
        dot_theta_scan = Theta_A / T_sc
        n_P = int((theta_a * f_r)/dot_theta_scan)
        print(f'扫描速率：{dot_theta_scan}; n_P: {n_P};')
        # A.非相参累积
        # A.1. 求单脉冲信噪比
        SNR_NCI_dB = dec_SNR_dB
        SNR_NCI = 10**(SNR_NCI_dB / 10.0)
        SNR_1 = SNR_NCI / (2*n_P) + np.sqrt(SNR_NCI**2/(4*n_P**2) + SNR_NCI/n_P)
        SNR_1_dB = 10*np.log10(SNR_1)
        print(f'SNR_1: {SNR_1}; {SNR_1_dB}dB;')
        # 计算非相参累积损失
        L_NCI = (1+SNR_1)/SNR_1
        L_NCI_dB = 10*np.log10(L_NCI)
        print(f'非相参累积损失：{L_NCI}; {L_NCI_dB}dB;')
        # 计算导弹单个脉冲能量
        print(f'R_m: {R_m}; G:{G}; lambda_:{lambda_}; sigmam: {sigmam};')
        E_m = ( (4*np.pi)**3*k*te*nf_dB*loss_dB*R_m**4*SNR_1 )/(G**2*lambda_**2*sigmam)
        E_a = ( (4*np.pi)**3*k*te*nf_dB*loss_dB*R_a**4*SNR_1 )/(G**2*lambda_**2*sigmaa)
        E = max(E_m, E_a)
        print(f'E_m: {E_m}; {E_a}; => {E};')
        # 求峰值功率
        P_t = E / tau
        print(f'pt: {P_t};')
        
        # 计算单脉冲SNR和积分损耗
        SNR_1 = (10**1.3)/(2*n_P) + np.sqrt(((10**1.3)**2)/(4*n_P*n_P) + (10**1.3)/n_P)
        LNCI = 10 * np.log10((1 + SNR_1)/SNR_1)
        loss_total = loss + LNCI
        
        print(f"计算得到的积分损耗: {LNCI:.2f} dB")
        print(f"总系统损耗: {loss_total:.2f} dB")
        
        # 生成距离范围 (15km到100km, 1000个点)
        range_vals = np.linspace(15e3, 100e3, 1000)  # 单位: 米
        range_km = range_vals / 1000  # 转换为公里
        
        # 计算SNR - 导弹目标
        snrm_nci = RadarCore.radar_eq(n_P*P_t, freq, G_dB, sigmam, te, B, nf, loss_total, range_vals)
        snrm_single = RadarCore.radar_eq(P_t, freq, G_dB, sigmam, te, B, nf, loss, range_vals)
        
        # 计算SNR - 飞机目标
        snra_nci = RadarCore.radar_eq(n_P*P_t, freq, G_dB, sigmaa, te, B, nf, loss_total, range_vals)
        snra_single = RadarCore.radar_eq(P_t, freq, G_dB, sigmaa, te, B, nf, loss, range_vals)
        
        # 创建图形
        plt.figure(figsize=(10, 8))
        
        # 导弹情况 - 上子图
        plt.subplot(2, 1, 1)
        plt.plot(range_km, snrm_nci, 'k-', label='With 7-pulse NCI')
        plt.plot(range_km, snrm_single, 'k-.', label='Single pulse')
        plt.grid(True)
        plt.legend()
        plt.ylabel('SNR - dB')
        plt.title('Missile case')
        
        # 飞机情况 - 下子图
        plt.subplot(2, 1, 2)
        plt.plot(range_km, snra_nci, 'k-', label='With 7-pulse NCI')
        plt.plot(range_km, snra_single, 'k-.', label='Single pulse')
        plt.grid(True)
        plt.legend()
        plt.ylabel('SNR - dB')
        plt.xlabel('Detection range - Km')
        plt.title('Aircraft case')
        
        plt.tight_layout()
        plt.show()